package com.chen.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.domain.UserAddress;
import com.chen.dto.R;
import com.chen.dto.UserAddressDto;
import com.chen.fegin.UserAddressFegin;
import com.chen.service.UserAddressService;
import com.chen.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: chen
 * @Date: 2021/4/26 11:20 AM
 * @Version 1.0
 */
@RestController
@Api(tags = "用户钱包地址")
@RequestMapping("/userAddress")
public class UserAddressController implements UserAddressFegin {

    @Autowired
    private UserAddressService userAddressService;


    @GetMapping("/getCoinAddress/{coidId}")
    public R<UserAddress> getCoinAddress(@PathVariable Long coidId){
        UserAddress userAddress = userAddressService.getOne(new LambdaQueryWrapper<UserAddress>()
                .eq(UserAddress::getUserId, UserUtil.getUser())
                .eq(UserAddress::getCoinId, coidId));
        return R.ok(userAddress);
    }

    @GetMapping
    @ApiOperation(value = "查阅用户的钱包地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户的Id"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页显示的条数")
    })
    public R<Page<UserAddress>> findByPage(@ApiIgnore Page<UserAddress> page, Long userId) {
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<UserAddress> userAddressPage = userAddressService.findByPage(page, userId);
        return R.ok(userAddressPage);
    }

    @Override
    public boolean saveUserAddress(List<UserAddressDto> userAddressDtos) {
        List<UserAddress> transform = userAddressDtos.stream().map(userAddressDto -> {
            UserAddress userAddress = new UserAddress();
            BeanUtils.copyProperties(userAddressDto, userAddress);
            return userAddress;
        }).collect(Collectors.toList());
        return userAddressService.saveBatch(transform);
    }
}
